<template>
    <div class="boxCard">
        <!-- 查询条件区域 -->
        <el-card class="box-card">
            <div class="title">
                <span></span>
                <p>查询条件</p>
            </div>
            <el-form label-width="120px">
                <el-row :gutter="12">
                    <el-col :span="6">
                        <el-form-item label="彩种编码: ">
                            <el-input v-model="searchObj.code" placeholder="请输入彩种编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="彩种名称: ">
                            <el-input v-model="searchObj.name" placeholder="请输入彩种名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" style="text-align: right">
                        <el-button type="primary" @click="getInit(1)">查询</el-button>
                        <el-button @click="reset">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 彩种列表区域 -->
        <el-card class="box-card" style="width: 100%; height: 80%">
            <div class="header">
                <div class="title">
                    <span></span>
                    <p>彩种列表</p>
                </div>
                <div>
                    <el-button type="primary" size="small" @click="showAddForm">新增</el-button>
                </div>
            </div>

            <el-table v-loading="loading" :data="lotteryList" height="85%">
                <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
                <el-table-column type="index" width="60" align="center" label="序号" fixed="left"></el-table-column>
                <el-table-column label="彩种编码" align="center" prop="code"></el-table-column>
                <el-table-column label="彩种名称" align="center" prop="name"></el-table-column>
                <el-table-column label="前区数量" align="center">
                    <template slot-scope="scope">{{ scope.row.front.count }}</template>
                </el-table-column>
                <el-table-column label="前区范围" align="center">
                    <template slot-scope="scope">{{ scope.row.front.min }}-{{ scope.row.front.max }}</template>
                </el-table-column>
                <el-table-column label="前区最小选择" align="center">
                    <template slot-scope="scope">{{ scope.row.front.minSelect }}</template>
                </el-table-column>
                <el-table-column label="前区允许重复" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.front.allowDuplicates">是</el-tag>
                        <el-tag type="info" v-else>否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="是否启用后区" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.hasBack">是</el-tag>
                        <el-tag type="info" v-else>否</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="后区数量" align="center">
                    <template slot-scope="scope">{{ scope.row.back ? scope.row.back.count : '-' }}</template>
                </el-table-column>
                <el-table-column label="后区范围" align="center">
                    <template slot-scope="scope">
                        <template v-if="scope.row.back">{{ scope.row.back.min }}-{{ scope.row.back.max }}</template>
                        <template v-else>-</template>
                    </template>
                </el-table-column>
                <el-table-column label="后区最小选择" align="center">
                    <template slot-scope="scope">{{ scope.row.back ? scope.row.back.minSelect : '-' }}</template>
                </el-table-column>
                <el-table-column label="后区允许重复" align="center">
                    <template slot-scope="scope">
                        <template v-if="scope.row.back">
                            <el-tag type="success" v-if="scope.row.back.allowDuplicates">是</el-tag>
                            <el-tag type="info" v-else>否</el-tag>
                        </template>
                        <template v-else>-</template>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
                <el-table-column label="操作" align="center" width="120" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" @click="updateData(scope.row)">修改</el-button>
                        <el-button type="text" @click="del(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <div style="text-align: right; margin-top: 10px">
                <el-pagination :current-page="searchObj.page" :page-sizes="[10, 50, 100, 200]"
                    :page-size="searchObj.size" layout="total, sizes, prev, pager, next, jumper"
                    :total="searchObj.total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"></el-pagination>
            </div>
        </el-card>

        <!-- 新增/编辑弹出框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogTableVisible">
            <el-form ref="formRef" label-width="120px" :model="formObj" :rules="rules">
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="彩种编码: " prop="code">
                            <el-input v-model="formObj.code" :disabled="isEdit" placeholder="请输入彩种编码"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="彩种名称: " prop="name">
                            <el-input v-model="formObj.name" placeholder="请输入彩种名称"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <div style="margin-left: 120px; margin-bottom: 10px; font-weight: bold;">前区配置</div>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="号码数量: " prop="front.count">
                            <el-input-number v-model="formObj.front.count" :min="1" :max="999"
                                placeholder="请输入数量"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="最小号码: " prop="front.min">
                            <el-input-number v-model="formObj.front.min" :min="0" :max="999"
                                placeholder="请输入最小号码"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="最大号码: " prop="front.max">
                            <el-input-number v-model="formObj.front.max" :min="formObj.front.min" :max="999"
                                placeholder="请输入最大号码"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="最小选择个数: " prop="front.minSelect">
                            <el-input-number v-model="formObj.front.minSelect" :min="1" :max="formObj.front.count"
                                placeholder="请输入最小选择个数"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="允许重复号码: " prop="front.allowDuplicates">
                            <el-switch v-model="formObj.front.allowDuplicates" active-text="是"
                                inactive-text="否"></el-switch>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <div style="margin-left: 120px; margin-bottom: 10px; font-weight: bold;">后区配置</div>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="是否启用后区: " prop="hasBack">
                            <el-switch v-model="hasBack" active-text="启用" inactive-text="不启用"
                                @change="handleBackChange"></el-switch>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="hasBack">
                        <el-form-item label="号码数量: " prop="back.count">
                            <el-input-number v-model="formObj.back.count" :min="1" :max="999"
                                placeholder="请输入数量"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="hasBack">
                        <el-form-item label="最小号码: " prop="back.min">
                            <el-input-number v-model="formObj.back.min" :min="0" :max="999"
                                placeholder="请输入最小号码"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="hasBack">
                        <el-form-item label="最大号码: " prop="back.max">
                            <el-input-number v-model="formObj.back.max" :min="formObj.back.min" :max="999"
                                placeholder="请输入最大号码"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="hasBack">
                        <el-form-item label="最小选择个数: " prop="back.minSelect">
                            <el-input-number v-model="formObj.back.minSelect" :min="1" :max="formObj.back.count"
                                placeholder="请输入最小选择个数"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="hasBack">
                        <el-form-item label="允许重复号码: " prop="back.allowDuplicates">
                            <el-switch v-model="formObj.back.allowDuplicates" active-text="是"
                                inactive-text="否"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div style="margin-top: 10px; text-align: center">
                <el-button type="primary" @click="confirm">确定</el-button>
                <el-button @click="dialogTableVisible = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { addLotteryType, deleteLotteryType, getAllLotteryTypes, updateLotteryType } from '@/api/lottery_manage';
import { Message } from 'element-ui';
export default {
    data() {
        // 后区字段验证函数
        const validateBackField = (rule, value, callback) => {
            if (!this.hasBack) {
                callback();
                return;
            }
            if (!value) {
                callback(new Error(rule.message));
            } else {
                callback();
            }
        };

        return {
            searchObj: {
                page: 1,
                size: 10,
                total: 0,
                code: '',
                name: ''
            },
            lotteryList: [],
            loading: false,
            dialogTableVisible: false,
            dialogTitle: '新增彩种',
            isEdit: false,
            hasBack: true,  // 控制是否启用后区的开关
            formObj: {
                code: '',
                name: '',
                front: {
                    count: 1,
                    min: 1,
                    max: 10,
                    minSelect: 1,
                    allowDuplicates: false
                },
                back: {
                    count: 1,
                    min: 1,
                    max: 5,
                    minSelect: 1,
                    allowDuplicates: false
                },
                createTime: ''
            },
            rules: {
                code: [
                    { required: true, message: '请输入彩种编码', trigger: 'blur' },
                    { pattern: /^[a-zA-Z0-9]+$/, message: '编码只能包含字母和数字', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入彩种名称', trigger: 'blur' }
                ],
                'front.count': [
                    { required: true, message: '请输入前区号码数量', trigger: 'blur' }
                ],
                'front.min': [
                    { required: true, message: '请输入前区最小号码', trigger: 'blur' }
                ],
                'front.max': [
                    { required: true, message: '请输入前区最大号码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (value <= this.formObj.front.min) {
                                callback(new Error('最大号码必须大于最小号码'));
                            } else if (!this.formObj.front.allowDuplicates && (value - this.formObj.front.min + 1 < this.formObj.front.count)) {
                                callback(new Error('号码范围不足以选择指定数量的不重复号码'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                'front.minSelect': [
                    { required: true, message: '请输入前区最小选择个数', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (value < 1) callback(new Error('最小选择个数不能小于1'));
                            else if (value > this.formObj.front.count) callback(new Error(`不能大于前区号码总数(${this.formObj.front.count})`));
                            else callback();
                        },
                        trigger: 'blur'
                    }
                ],
                'back.count': [
                    { validator: validateBackField, message: '请输入后区号码数量', trigger: 'blur' }
                ],
                'back.min': [
                    { validator: validateBackField, message: '请输入后区最小号码', trigger: 'blur' }
                ],
                'back.max': [
                    { validator: validateBackField, message: '请输入后区最大号码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.hasBack) { callback(); return; }
                            if (value <= this.formObj.back.min) {
                                callback(new Error('最大号码必须大于最小号码'));
                            } else if (!this.formObj.back.allowDuplicates && (value - this.formObj.back.min + 1 < this.formObj.back.count)) {
                                callback(new Error('号码范围不足以选择指定数量的不重复号码'));
                            } else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                'back.minSelect': [
                    { validator: validateBackField, message: '请输入后区最小选择个数', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.hasBack) { callback(); return; }
                            if (value < 1) callback(new Error('最小选择个数不能小于1'));
                            else if (value > this.formObj.back.count) callback(new Error(`不能大于后区号码总数(${this.formObj.back.count})`));
                            else callback();
                        },
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    mounted() {
        this.getInit();
    },
    methods: {
        async getInit(page) {
            this.searchObj.page = page || this.searchObj.page;
            this.loading = true;
            try {
                const response = await getAllLotteryTypes(this.searchObj);
                this.loading = false;
                if (response.code === 20000) {
                    this.lotteryList = response.data || [];
                    this.searchObj.total = response.total || 0;
                } else {
                    Message.error('获取彩种列表失败: ' + (response.msg || '未知错误'));
                }
            } catch (error) {
                this.loading = false;
                console.error('获取彩种列表出错:', error);
                Message.error('获取彩种列表失败，请重试');
            }
        },
        reset() {
            this.searchObj = {
                page: 1,
                size: 10,
                total: this.searchObj.total,
                code: '',
                name: ''
            };
            this.getInit();
        },
        handleBackChange(checked) {
            this.hasBack = checked; // 更新hasBack状态
            if (!checked) {
                this.formObj.back = null;
            } else {
                this.formObj.back = {
                    count: 1,
                    min: 1,
                    max: 5,
                    minSelect: 1,
                    allowDuplicates: false
                };
            }
            this.$nextTick(() => {
                this.$refs.formRef && this.$refs.formRef.clearValidate([
                    'back.count', 'back.min', 'back.max', 'back.minSelect'
                ]);
            });
        },
        showAddForm() {
            this.dialogTableVisible = true;
            this.dialogTitle = '新增彩种';
            this.isEdit = false;
            this.hasBack = true; // 默认启用后区
            this.formObj = {
                code: '',
                name: '',
                front: {
                    count: 1,
                    min: 1,
                    max: 10,
                    minSelect: 1,
                    allowDuplicates: false
                },
                back: {
                    count: 1,
                    min: 1,
                    max: 5,
                    minSelect: 1,
                    allowDuplicates: false
                },
                createTime: ''
            };
            this.$nextTick(() => {
                this.$refs.formRef && this.$refs.formRef.resetFields();
            });
        },
        updateData(row) {
            this.$nextTick(() => {
                this.$refs.formRef && this.$refs.formRef.resetFields();
            });
            this.formObj = { ...JSON.parse(JSON.stringify(row)) };
            this.dialogTableVisible = true;
            this.dialogTitle = '编辑彩种';
            this.isEdit = true;
            // 从数据中读取hasBack状态，关键修复点
            this.hasBack = row.hasBack !== undefined ? row.hasBack : true;

            if (!this.formObj.back) {
                this.formObj.back = {
                    count: 1,
                    min: 1,
                    max: 5,
                    minSelect: 1,
                    allowDuplicates: false
                };
            }
            if (this.formObj.front.allowDuplicates === undefined) {
                this.formObj.front.allowDuplicates = false;
            }
            if (this.formObj.back && this.formObj.back.allowDuplicates === undefined) {
                this.formObj.back.allowDuplicates = false;
            }

        },
        confirm() {
            this.$refs.formRef.validate(async (valid) => {
                if (valid) {
                    this.$confirm("确定提交吗？", "提示", {
                        cancelButtonText: "取消",
                        confirmButtonText: "确定",
                        type: "warning",
                    }).then(async () => {
                        // 关键修复点：将hasBack字段加入提交数据
                        let submitData = {
                            ...this.formObj,
                            hasBack: this.hasBack  // 传递hasBack状态到后端
                        };

                        if (!this.hasBack) {
                            submitData.back = null;
                        }

                        const response = this.isEdit
                            ? await updateLotteryType(submitData)
                            : await addLotteryType({ ...submitData, createTime: new Date().toISOString() });

                        if (response.code === 20000) {
                            Message.success(this.isEdit ? '更新成功' : '新增成功');
                            this.dialogTableVisible = false;
                            this.getInit();
                        } else {
                            Message.error((this.isEdit ? '更新' : '新增') + '失败: ' + (response.msg || '未知错误'));
                        }
                    });
                }
            });
        },
        del(row) {
            this.$confirm(`确定要删除彩种"${row.name}"吗？`, "提示", {
                cancelButtonText: "取消",
                confirmButtonText: "确定",
                type: "warning",
            }).then(async () => {
                try {
                    const response = await deleteLotteryType(row);
                    if (response.code === 20000) {
                        Message.success('删除成功');
                        this.getInit();
                    } else {
                        Message.error('删除失败: ' + (response.msg || '未知错误'));
                    }
                } catch (error) {
                    console.error('删除彩种出错:', error);
                    Message.error('删除彩种失败，请重试');
                }
            });
        },
        handleSizeChange(size) {
            this.searchObj.size = size;
            this.getInit(1);
        },
        handleCurrentChange(page) {
            this.getInit(page);
        }
    }
};
</script>

<style scoped>
>>>.el-card__body {
    padding: 20px;
    width: 100%;
    height: 100%;
}

.title {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.title span {
    display: inline-block;
    width: 4px;
    height: 18px;
    background-color: #1890ff;
    margin-right: 8px;
    border-radius: 2px;
}

.title p {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}
</style>
